package br.financeiro.dao;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import br.financeiro.R;
import br.financeiro.entities.Mail;
import br.financeiro.entities.Person;
import br.financeiro.entities.Phone;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

/**
 * Database helper class used to manage the creation and upgrading of your
 * database. This class also usually provides the DAOs used by the other
 * classes.
 */
public class DBHelper extends OrmLiteSqliteOpenHelper {

	private static final String DATABASE_NAME = "DataBase.db";
	private static final int DATABASE_VERSION = 13;

	private Dao<Person, Integer> personDAO = null;
	private Dao<Phone, Integer> phoneDAO = null;
	private Dao<Mail, Integer> mailDAO = null;

	public DBHelper( Context context ) {
		super( context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config );
	}

	@Override
	public void onCreate( SQLiteDatabase db, ConnectionSource connectionSource ) {
		try {
			TableUtils.createTable( connectionSource, Person.class );
			TableUtils.createTable( connectionSource, Phone.class );
			TableUtils.createTable( connectionSource, Mail.class );
		} catch ( SQLException e ) {
			throw new RuntimeException( e );
		}
	}

	@Override
	public void onUpgrade( SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion ) {
		try {
			TableUtils.dropTable( connectionSource, Mail.class, true );
			TableUtils.dropTable( connectionSource, Phone.class, true );
			TableUtils.dropTable( connectionSource, Person.class, true );
			onCreate( db, connectionSource );
		} catch ( SQLException e ) {
			throw new RuntimeException( e );
		}
	}

	public Dao<Person, Integer> getPersonDao() throws SQLException {
		if ( personDAO == null ) {
			personDAO = getDao( Person.class );
		}
		return personDAO;
	}

	public Dao<Mail, Integer> getMailDao() throws SQLException {
		if ( mailDAO == null ) {
			mailDAO = getDao( Mail.class );
		}
		return mailDAO;
	}

	public Dao<Phone, Integer> getPhoneDao() throws SQLException {
		if ( phoneDAO == null ) {
			phoneDAO = getDao( Phone.class );
		}
		return phoneDAO;
	}

	@Override
	public void close() {
		super.close();
		personDAO = null;
		phoneDAO = null;
		mailDAO = null;
	}
}
